<template lang="html">
  <div class="UpImg">
    <!-- 图像 -->
    <div v-show="false">
      <input ref="imgInput" type="file" accept="image/*" @change="upImg" >
    </div>
  </div>
</template>

<script>
import lrz from 'lrz'

export default {
  data() {
    return {
    }
  },
  mounted() {
  },
  methods: {
    click() {
      this.$refs.imgInput.click()
    },
    upImg() {
      let files = this.$refs.imgInput.files[0]

      this.$refs.imgInput.value = null

      if (files === undefined) {
        this.$Toast('请选择图片', 'error')
        return
      }

      this.upImgFile(files).then((res) => {
        this.$emit('upSuccess', res)
      })

    },
    upImgFile(file) {
      let toastId = this.$Toast('正在上传中', 'message', 10000)

      return new Promise((resolve, reject) => {
        lrz(file).then((res) => {
          let formdata = new FormData()
          formdata.append('img', res.file)

          flyio.post('/imgs/upimg', formdata).then((res) => {
            if (res.code === 200) {
              this.$Toast('上传成功')
              resolve(res.url)
            } else {
              this.$Toast('上传失败', 'error')
              reject('上传失败')
            }
          }).catch((res) => {
            this.$Toast('系统错误', 'error')
            reject('系统错误')
          }).finally(() => {
            this.$Toast(toastId);
          })
        })
      })
    },
  },
}
</script>

<style lang="css" scoped>
</style>
